import React from 'react';
import routes from './routes';
import {importData} from './api';
import styles from './style.css';
import PropTypes from 'prop-types';
import {validateAdd} from './validator';
import ImportPanel from './ImportPanel';
import {injectIntl, formatMessage} from './intl';
import {computeSelectedRows, uuid} from './utils';
import {TABLE, FIXED_COLUMN_WIDTH} from '../constants';
import SearchInput from 'Shared/components/SearchInput';
import PartSelectPanel from '../PartStockDealer/PartSelectPanel';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import {Button, Spin, Card, Table, message as msg, Row, Col, Popconfirm} from 'antd';
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        isValidate: false,
        details: [],
        detailsId: '',
        showIncreImport: false,
        showPartSelectPanel: false,
        selectedRowKeys: [],
        selectedRows: []
    };
    componentDidMount() {
        this.ismounted = true;
    }
    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }
    submit = () => {
        const isValid = validateAdd(this.state.selectedRows);
        if(!isValid) return;
        this.setState({loading: true});
        importData({details: this.state.selectedRows.map(v => ({
            id: v.dealerId,
            partId: v.partId
        }))}).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    }
    // eslint-disable-next-line react/sort-comp
    onDeleteAll = () => this.setState({
        details: [],
        selectedRows: []
    });
    onDeletePart = e => {
        const id = e.target.dataset.id;
        const tmp = this.state.details.filter(d => d.id !== id);
        const rows = this.state.selectedRows.filter(d => d.id !== id);
        this.setState({
            selectedRows: [...rows],
            details: [...tmp],
            hasOperat: true
        });
    }
    onIncreImport = () => {
        const parts = this.state.details || [];
        if(parts && parts.findIndex(v => v.dealerId === '') === 0)
            return msg.warn(formatMessage({
                id: 'newPanel.message.dealer',
                defaultMessage: '请选择总代！'
            }));
        if(parts && parts.findIndex(v => v.partId === '') === 0)
            return msg.warn(formatMessage({
                id: 'newPanel.message.parts',
                defaultMessage: '请选择备件号！'
            }));
        this.setState({showIncreImport: true});
    };
    onCloseIncreImport = () => this.setState({showIncreImport: false});
    increImportChange = records => {
        const parts = this.state.details || [];
        if(records.payload.content) {
            // eslint-disable-next-line array-callback-return
            records.payload.content.map(item => {
                const index = parts.findIndex(v => v.partId === item.partId);
                if(index === -1)
                    parts.push({
                        id: uuid(),
                        dealerId: item.id,
                        dealerCode: item.dealerCode,
                        dealerName: item.dealerName,
                        partId: item.partId,
                        partCode: item.partCode,
                        partName: item.partName
                    });
            });
            this.setState({
                showIncreImport: false,
                details: [...parts],
            });
            msg.success(formatMessage({
                id: 'newPanel.msg.increImport',
                defaultMessage: '增量导入成功'
            }));
        }
    }
    onClickAddBtn = () => {
        const details = this.state.details;
        this.setState({
            details: [
                ...details,
                {
                    id: uuid(),
                    dealerId: '',
                    dealerCode: '',
                    dealerName: '',
                    partId: '',
                    partCode: '',
                    partName: ''
                }
            ]
        });
    };
    onSelectDealer = (data, id) => {
        const details = this.state.details;
        const selectedRows = this.state.selectedRows;
        const tmp = details.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    dealerId: data.id,
                    dealerCode: data.code,
                    dealerName: data.name
                });
            return d;
        });
        const rows = selectedRows.map(d => {
            if(d.id === id)
                return Object.assign({}, d, {
                    dealerId: data.id,
                    dealerCode: data.code,
                    dealerName: data.name
                });
            return d;
        });
        this.setState({
            details: tmp,
            selectedRows: rows,
            hasOperat: true
        });
    }
    onClickSearchBtn = id => this.setState({
        showPartSelectPanel: true,
        detailsId: id
    });
    onClosePartSelectPanel = () => this.setState({showPartSelectPanel: false});
    onSelectPart = records => {
        const details = this.state.details || [];
        const selectedRows = this.state.selectedRows || [];
        const index = details.findIndex(v => v.partId === records.partId);
        if(index === 0)
            return msg.warn(formatMessage({
                id: 'newPanel.message.part',
                defaultMessage: '已存在该备件！'
            }));
        const tmp = details.map(d => {
            if(d.id === this.state.detailsId)
                return Object.assign({}, d, {
                    partName: records.partName,
                    partCode: records.partCode,
                    partId: records.partId
                });
            return d;
        });
        const rows = selectedRows.map(d => {
            if(d.id === this.state.detailsId)
                return Object.assign({}, d, {
                    partName: records.partName,
                    partCode: records.partCode,
                    partId: records.partId
                });
            return d;
        });
        this.setState({
            details: tmp,
            hasOperat: true,
            selectedRows: rows,
            showPartSelectPanel: false
        });
    }
    render() {
        const {onCancel} = this.props;
        const {details, loading, showIncreImport, showPartSelectPanel} = this.state;
        const columns = [
            {
                title: formatMessage({
                    id: 'newPanel.column.dealerCode',
                    defaultMessage: '总代号'
                }),
                dataIndex: 'dealerCode',
                width: 300,
                render: (text, record) => <DealerSelectPanel
                    value={record.dealerId ? {
                        id: record.id,
                        code: text,
                        name: record.dealerName
                    } : null}
                    allowClear={false}
                    onSelect={data => this.onSelectDealer(data, record.id)} />
            }, {
                title: formatMessage({
                    id: 'newPanel.column.partCode',
                    defaultMessage: '备件号'
                }),
                dataIndex: 'partCode',
                width: 300,
                render: (text, record) => <SearchInput
                    value={record.partCode}
                    id={record.id}
                    onClickSearchBtn={() => this.onClickSearchBtn(record.id)}/>
            }, {
                title: formatMessage({
                    id: 'newPanel.column.partName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'partName'
            }, {
                title: details && details.length > 0
                    ? (<Popconfirm placement="topRight" title={formatMessage({
                        id: 'newPanel.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{formatMessage({
                            id: 'newPanel.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>)
                    : <a>{formatMessage({
                        id: 'newPanel.column.empty',
                        defaultMessage: '清空'
                    })}</a>,
                dataIndex: 'id',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => <a data-id={text} onClick={this.onDeletePart}>{formatMessage({
                    id: 'newPanel.column.delete',
                    defaultMessage: '删除'
                })}</a>
            }
    
        ];
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            },
            getCheckboxProps: record => ({
                disabled: this.state.selectedRows.some(item => item === record.id)
            }),
        };
        return (
            <div className={styles.detail}>
                <Spin spinning={loading}>
                    <Card
                        title={formatMessage({
                            id: 'newPanel.details.title',
                            defaultMessage: '可提报资源导入编辑'
                        })}
                        extra={<Button
                            size="small"
                            onClick={this.onIncreImport}>
                            {formatMessage({
                                id: 'newPanel.operation.increImport',
                                defaultMessage: '增量导入'
                            })}
                        </Button>}>
                        <Button
                            type="dashed"
                            icon="plus"
                            block
                            className={styles.plusBtn}
                            onClick={this.onClickAddBtn}>
                            {formatMessage({
                                id: 'newPanel.operation.new',
                                defaultMessage: '新增'
                            })}
                        </Button>
                        <Table
                            className="white-space-nowrap"
                            rowKey="id"
                            columns={columns}
                            pagination={true}
                            rowSelection={rowSelection}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                </Spin>
                <Card className={styles.optionBtn}>
                    <Row>
                        <Col className="col-align-right">
                            <Button
                                key="audit"
                                loading={loading}
                                onClick={this.submit}
                                className={styles.btnMargin}
                                type="primary">
                                {formatMessage({
                                    id: 'newPanel.btn.submit',
                                    defaultMessage: '提交'
                                })}
                            </Button>
                        </Col>
                    </Row>
                </Card>
                <div className="page-toolbar">
                    <Button type="primary" disabled={loading} onClick={onCancel}>
                        {formatMessage({
                            id: 'newPanel.btn.return',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
                {
                    showIncreImport &&
                        <ImportPanel
                            selectKey={'1'}
                            onCancel={this.onCloseIncreImport}
                            onImportChange={this.increImportChange} />
                }
                {
                    showPartSelectPanel &&
                        <PartSelectPanel
                            type="dealerPartResource"
                            onCancel={this.onClosePartSelectPanel}
                            onSelect={this.onSelectPart} />
                }
            </div>
        );
    }
}
NewPanel.propTypes = {
    conditions: PropTypes.object.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {clearData, querySearch, clearBatchData} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const mapStateToProps = state => ({
    conditions: getConditions(state),
    mergeList: state.getIn(['page', 'ui', 'mergeDetails'])
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    successReturn: () => {
        dispatch(querySearch());
        dispatch(clearBatchData());
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
